package cn.zero.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.thoughtworks.xstream.core.util.Base64Encoder;

public class AppStringUtils {

	private static DecimalFormat decimalFormat;

	public final static String ROLE_STORE = "store";
	public final static String ROLE_STORE_SERVER = "storeServer";

	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuilder sb = new StringBuilder("");
		for (int l = 0; l < length; l++) {
			int i = random.nextInt(3);
			int j = 0;
			if (i == 0) {
				j = random.nextInt(10);
			} else if (i == 1) {
				j = random.nextInt(26) + (int) 'a';
			} else {
				j = random.nextInt(26) + (int) 'A';
			}
			sb.append(j < 10 ? String.valueOf(j) : (char) j);
		}

		return sb.toString();
	}

	public static void doOutput(OutputStream out, byte[] data, int len)
			throws IOException {
		int dataLen = data.length;
		int off = 0;
		while (off < data.length) {
			if (len >= dataLen) {
				out.write(data, off, dataLen);
				off += dataLen;
			} else {
				out.write(data, off, len);
				off += len;
				dataLen -= len;
			}
			// 刷新缓冲区
			out.flush();
		}
	}

	@SuppressWarnings("unchecked")
	public static Map<String, String> XMLToMap(String xml)
			throws DocumentException {
		Map<String, String> map = new TreeMap<String, String>();
		Document document = DocumentHelper.parseText(xml);
		Element rootElement = document.getRootElement();
		List<Element> elementList = rootElement.elements();
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		return map;
	}

	public static String mapToXMLString(Map<String, String> map) throws IOException {
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		Element root = document.addElement("xml");
		for (Entry<String, String> kv : map.entrySet()) {
			Element ele = root.addElement(kv.getKey());
			ele.addText(kv.getValue());
		}
		return AppStringUtils.XMLToString(document);
	}
	
	public static Document mapToXML(Map<String, String> map) throws IOException {
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		Element root = document.addElement("xml");
		for (Entry<String, String> kv : map.entrySet()) {
			Element ele = root.addElement(kv.getKey());
			ele.addText(kv.getValue());
		}
		return document;
	}
	
	public static String XMLToString(Document document) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		OutputFormat format = new OutputFormat("", true, "utf-8");
		XMLWriter writer = new XMLWriter(out, format);
		writer.write(document);
		return out.toString("utf-8");
	}

	/**
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static String convertStreamToString(InputStream inStream)
			throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inStream, "UTF-8"));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		inStream.close();
		return sb.toString();
	}

	public static String getTtimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
	
	/**
	 * 获取LocalDateTime "yyyy-MM-dd HH:mm:ss" 的格式器
	 * @return
	 */
	public static DateTimeFormatter getDateTimeFormatter() {
		return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 获取LocalDateTime "yyyy-MM-dd" 的格式器
	 * @return
	 */
	public static DateTimeFormatter getDateFormatter() {
		return DateTimeFormatter.ofPattern("yyyy-MM-dd");
	}
	
	public static String md5(String initStr) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			Base64Encoder encoder =  new Base64Encoder();
			return encoder.encode(md.digest(initStr.getBytes("UTF-8")));
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 用于double,float等格式化成两位数小数点
	 * @return
	 */
	public static DecimalFormat getDecimalFormat() {
		if (decimalFormat == null) {
			decimalFormat = new DecimalFormat("#0.00");
		}
		return decimalFormat;
	}
	
}


